<template>
  <div class="taskcreatecom">
    <div class="searchcondition resultlist">
      <el-scrollbar>
        <el-button type="primary" size="default" @click="testClick()">test</el-button>
        <el-button type="primary" size="default" @click="testClick1()">test1</el-button>
      </el-scrollbar>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, watch } from "vue";
import { useWebSocket } from "@vueuse/core";
import useTaskList from "./useTaskList";
import { httpRequest } from "@/api/httpRequest";
import { useEarthStore } from "@/stores/earth";
import _ from "lodash";
import { reactive } from "vue";
import dayjs from "dayjs";
import { apiList } from "@/api/apiList";
import * as turf from "@turf/turf";

const { courseAngle } = useTaskList();
const earthStore = useEarthStore();

import plot from "@/components/common/Earth/plot/plot.js";
import { getMouseInfo, EventCode } from "@/components/common/Earth/plot/utiles.js";
import { ElMessage } from "element-plus";

let _p = {};
let _layer = {};

setTimeout(() => {
  let layer = new Cesium.CustomDataSource("plotlayer");
  viewer.dataSources.add(layer);
  _layer = layer;
  _p = new plot(viewer);
}, 1000);

function testClick1(params) {
  console.log(_p.plotlist);
  let e = _p.plotlist[Object.keys(_p.plotlist)[0]];
  console.log(e);
  e.createPoints();
  _p.edit(e);
}

function testClick(params) {
  let d = [
    {
      type: "polygonmark",
      data: [
        { lng: 113.4, lat: 34.5, alt: 0 },
        { lng: 113.5, lat: 34.6, alt: 0 },
        { lng: 113.5, lat: 34.5, alt: 0 },
        { lng: 113.4, lat: 34.5, alt: 0 },
      ],
    },
  ];

  _p.loadData(d);
}

onMounted(() => {
  addLayer();
  addLineEvent();
});

let h = {};

window.isedit = false;

window.editend = function (item) {
  console.log(window.editobj);



  if (window.editobj == "") {
    return
  }
  let resposstr = "";
  let respos = window.editobj.wgs84pos.map(item => {
    return `${item.lng},${item.lat}`;
    // return [item.lng, item.lat]
  });

  resposstr = respos.join(" ");

  console.log(resposstr);
  
  // return

  // 调用 wfs 保存接口

  let xmlparams = `
  <wfs:Transaction service="WFS" version="1.0.0"
    xmlns:topp="http://www.openplans.org/topp"
    xmlns:ogc="http://www.opengis.net/ogc"
    xmlns:gml="http://www.opengis.net/gml"
    xmlns:wfs="http://www.opengis.net/wfs">
    <wfs:Update typeName="test_tif:test">
      <wfs:Property>
        <wfs:Name>the_geom</wfs:Name>
        <wfs:Value>
          <gml:Polygon srsName="EPSG:4326">
          <gml:outerBoundaryIs>
            <gml:LinearRing>
              <gml:coordinates>
                ${resposstr}
              </gml:coordinates>
            </gml:LinearRing>
          </gml:outerBoundaryIs>
        </gml:Polygon>
        </wfs:Value>
      </wfs:Property>
      <ogc:Filter>
        <PropertyIsEqualTo>
          <PropertyName>id</PropertyName>
          <Literal>${ploteidskv[window.editobj.id]}</Literal>
        </PropertyIsEqualTo>
      </ogc:Filter>
    </wfs:Update>
  </wfs:Transaction>
  `;

  // httpRequest
  //   .post(
  //     // "/jiejing/geoserver/test_tif/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=test_tif%3Ajuhetuceng&maxFeatures=50&outputFormat=application%2Fjson&BBOX=" +
  //     "/geoserver/wfs",
  //     {
  //       headers: {
  //         "Content-Type": "text/xml",
  //       },
  //       params: xmlparams,
  //     }
  //   )
  //   .then(res => {});
  httpRequest({
    method: 'post',
    url: '/geoserver/wfs',
    headers: {
      'Content-Type': 'text/xml'
    },
    data: xmlparams
  }).then(res => {
    if (res.indexOf('SUCCESS') != -1) {
      ElMessage.success("更新成功")
      window.editobj = ""
      _p.removeall()
      layerRef.enabled = false
      setTimeout(() => {
        layerRef.enabled = true
      }, 0);
    }else{
      ElMessage({
        message: "更新失败：" + res,
        duration: 2000 * 10,
      })
      window.editobj = ""
      _p.removeall()

    }
  })
};

window.editobj = "";

let ploteidskv = {}

function addLineEvent(params) {
  h = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  h.setInputAction(movement => {
    setTimeout(() => {
      if (!window.isedit) {
        let res = getMouseInfo(movement.position);
        var point = turf.point([
          res.wgs84SurfacePosition.lng,
          res.wgs84SurfacePosition.lat,
        ]);
        var buffered = turf.buffer(point, 5, { units: "meters", steps: 1 });
        var bbox = turf.bbox(buffered);
        httpRequest
          .get(
            // "/jiejing/geoserver/test_tif/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=test_tif%3Ajuhetuceng&maxFeatures=50&outputFormat=application%2Fjson&BBOX=" +
            "/geoserver/test_tif/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=test_tif%3Atest&maxFeatures=50&outputFormat=application%2Fjson&BBOX=" +
              bbox.join(",")
          )
          .then(res => {
            // 添加对象到场景
            console.log(res);
            if (res.features.length != 0) {
              let d = [
                {
                  type: "polygonmark",
                  data: [
                    // { lng: 113.4, lat: 34.5, alt: 0 },
                  ],
                },
              ];
              res.features[0].geometry.coordinates[0][0].map(item => {
                d[0].data.push({ lng: item[0], lat: item[1], alt: 0 });
              });
              _p.loadData(d);
              _p.edit(d[0].ide)
              window.editobj = d[0].ide
              ploteidskv[d[0].id] = res.features[0].properties.id
            }
          });
      }
    }, 50);
  }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}

let basemapSource = ''
let layerRef = ''

function addLayer() {
  let imgopt = {
    url: "/geoserver/test_tif/wms",
    layers: "test_tif:test",
    parameters: {
      transparent: true, //务必设为true。否则不显示底图
      format: "image/png",
      srs: "EPSG:4326",
    },
  };

  basemapSource = new Cesium.WebMapServiceImageryProvider(imgopt);

  earth.sceneTree.root.children.push({
    ref: "linelayer",
    czmObject: {
      xbsjType: "Imagery",
      name: "linelayer",
      xbsjImageryProvider: {
        type: "WebMapServiceImageryProvider",
      },
    },
  });

  setTimeout(() => {
    layerRef = earth.sceneTree.$refs["linelayer"];
    layerRef.czmObject.xbsjImageryProvider.WebMapServiceImageryProvider._imageryProvider = basemapSource;
  }, 100);
}

function removeLayer(params) {
  // basemapSource.show = false
  // layerRef.enabled = false
}

function closewindow() {}

defineExpose({
  closewindow,
});
</script>
<style lang="scss" scoped>
.resultlist {
  // height: calc(100% - 135px);
  height: calc(100%);
}

.eachlevelitem {
  border: 1px solid white;
  width: 25px;
  height: 30px;
  cursor: pointer;

  &:hover {
    background-color: #3333;
  }
}

.searchcondition {
  // border: ;
  border: 1px solid white;
  padding: 10px;
  // cursor: pointer;
  // margin: 10px;
  box-sizing: border-box;
  border-radius: 5px;
}

.taskcreatecom {
  box-sizing: border-box;
  padding: 10px;
  height: 100%;
  // display: flex;
}
</style>
